package cn.sala.user.controller;

import cn.sala.distributedlock.redis.RedissLockUtil;
import cn.sala.user.domain.User;
import cn.sala.user.service.UserService;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/demo1")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @RequestMapping(value = "/test1/{name}", method = RequestMethod.GET)
    @ResponseBody
    public void test(@PathVariable("name") String name) {
        // 分布式锁
        RLock lock = RedissLockUtil.lock(name);
        try {
            boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (res) {
                logger.info("进入业务代码: " + name);
                List<User> userList = userService.findUserByName(name);
                if (userList != null) {
                    for (int i = 0; i < userList.size(); i++) {
                        User user = userList.get(i);
                        System.out.println(user.toString());
                    }
                }
            }
            lock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
